package com.wave.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wave.entity.Info;
import com.wave.service.InfoService;
import com.wave.utils.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/info")
public class InfoController {

    @Autowired
    private InfoService infoService;

    @PostMapping("create")
    public Integer createInfo(@RequestBody JSONObject requestJson)  {
        // System.out.println(requestJson);
        Info info = new Info();
        // 标题
        String title = requestJson.getString("title");
        info.setInfoTitle(title);
        // 时间
        Date dateTime = new Date(); // 现在时间 (Fri Dec 10 03:01:12 CST 2021)
//        DateFormat formatDateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        Date dateTime = formatDateTime.parse("2021-12-10 02:26:55");
//        Date dateTimeFor =  formatDateTime.parse(formatDateTime.format(dateTime));  //转设定的时间格式 再转Date格式
        Timestamp timestamp = new Timestamp(dateTime.getTime()); //利用timestamp格式直接转换
        info.setInfoCreateDate(timestamp);
        info.setInfoLastDate(timestamp);
        // 正文
        String text = requestJson.getString("text");
        info.setInfoText(text);
        // 作者
        String Author = requestJson.getString("userAccount");
        info.setInfoAuthor(Author);
        // 推荐类型
        String type = requestJson.getString("targets");
        info.setInfoType(type);
        if (type.equals("2")){
            // 系部
            String departments = requestJson.getString("departments");
            if (!departments.equals("null")){
                departments = departments.substring(1,departments.length()-1);
                info.setInfoTargetId(departments);
            }
        }else if (type.equals("3")){
            // 生活
            String quarters = requestJson.getString("quarters");
            if (!quarters.equals("null")){
                quarters = quarters.substring(1,quarters.length()-1);
                info.setInfoTargetId(quarters);
            }
        }
        // 首页
        String index = requestJson.getString("index");
        if (index.length() > 2){
            index = index.substring(1,index.length()-1);
            if (index.equals("1")){
                int rankNum = infoService.countIndex() + 1;
                String rank = String.valueOf(rankNum);
                info.setInfoRank(rank);
            }
        }
        // 轮播
        String swiper = requestJson.getString("swiper");
        if (swiper.length() > 2){
            swiper = swiper.substring(1,swiper.length()-1);
            if (swiper.equals("1")){
                int swiperNum = infoService.countSwiper() + 1;
                String swiperStr = String.valueOf(swiperNum);
                info.setInfoSwiper(swiperStr);
            }
        }
        // 头图
        String headImg = requestJson.getString("headImg");
        info.setInfoHeadImg(headImg);

        System.out.println(info.toString());
        return infoService.createInfo(info);
    }

    @PostMapping("alter")
    public int alterInfo(@RequestBody JSONObject requestJson)  {
        // System.out.println(requestJson);
        Info info = new Info();
        // 编号
        int infoId = requestJson.getInteger("infoId");
        info.setInfoId(infoId);
        // 标题
        String title = requestJson.getString("title");
        info.setInfoTitle(title);
        // 时间
        Date dateTime = new Date(); // 现在时间 (Fri Dec 10 03:01:12 CST 2021)
        Timestamp timestamp = new Timestamp(dateTime.getTime()); //利用timestamp格式直接转换
        info.setInfoLastDate(timestamp);
        // 正文
        String text = requestJson.getString("text");
        info.setInfoText(text);
        // 作者
        String Author = requestJson.getString("userAccount");
        info.setInfoAuthor(Author);
        // 推荐类型
        String type = requestJson.getString("targets");
        info.setInfoType(type);
        if (type.equals("2")){
            // 系部
            String departments = requestJson.getString("departments");
            if (!departments.equals("null")){
                departments = departments.substring(1,departments.length()-1);
                info.setInfoTargetId(departments);
            }
        }else if (type.equals("3")){
            // 生活
            String quarters = requestJson.getString("quarters");
            if (!quarters.equals("null")){
                quarters = quarters.substring(1,quarters.length()-1);
                info.setInfoTargetId(quarters);
            }
        }
        // 首页
        String index = requestJson.getString("index");
        if (index.length() > 2){
            index = index.substring(1,index.length()-1);
            if (index.equals("1")){
                int rankNum = infoService.countIndex() + 1;
                String rank = String.valueOf(rankNum);
                info.setInfoRank(rank);
            }
        }
        // 轮播
        String swiper = requestJson.getString("swiper");
        if (swiper.length() > 2){
            swiper = swiper.substring(1,swiper.length()-1);
            if (swiper.equals("1")){
                int swiperNum = infoService.countSwiper() + 1;
                String swiperStr = String.valueOf(swiperNum);
                info.setInfoSwiper(swiperStr);
            }
        }
        // 头图
        String headImg = requestJson.getString("headImg");
        info.setInfoHeadImg(headImg);

        System.out.println(info.toString());
        return infoService.alterInfo(info);
    }

    @PostMapping("delete")
    public int deleteInfo(@RequestBody JSONObject requestJson)  {
        int infoId = requestJson.getInteger("infoId");
        System.out.println("删除资讯编号："+infoId);
        return infoService.deleteInfo(infoId);
    }

    @PostMapping("deleteList")
    public boolean deleteInfoList(@RequestBody List<Integer> infoIdList)  {
        try{
            for (int infoId : infoIdList) {
                System.out.println("删除资讯编号："+infoId);
                infoService.deleteInfo(infoId);
            }
            return true;
        }
        catch (Exception e){
            return false;
        }
    }

    @RequestMapping("indexInfo")
    public List<Info> getIndexInfo(){
        System.out.println("首页资讯");
        return infoService.getIndexInfo();
    }

    @RequestMapping("swiper")
    public List<Info> getSwiper(){
        System.out.println("轮播图");
        return infoService.getSwiper();
    }

    @RequestMapping("searchTitle")
    public List<Info> searchInfoTitle(@RequestBody JSONObject requestJson){
        String infoTitle = requestJson.getString("infoTitle");
        String title = "%" + infoTitle + "%";
        //System.out.println(infoTitle);
        return infoService.searchInfoTitle(title);
    }

    @GetMapping("getInfoDetail")
    public Info getInfoDetail(@RequestParam("id") int infoId){
        System.out.println("获得资讯详情页编号："+infoId);
        return infoService.getInfoDetail(infoId);
    }

    @PostMapping("uploadImg")
    public JSONObject uploadImgInfo(@RequestParam(value = "image") MultipartFile uploadFile) {
        // 每天一个文件夹保存图片
        Date date = new Date(); // 现在时间 (Fri Dec 10 03:01:12 CST 2021)
        DateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd");
        String dateString =  formatDate.format(date);
        String pathPart = "infoImage/" + dateString + "/";
        String pathName = "D:/springboot/" + pathPart;//存储文件的本地绝对路径
        File file = new File(pathName);
        file.mkdirs();
        String fileName = uploadFile.getOriginalFilename();//获取文件名（包括后缀）
        pathName = pathName + fileName;
        try {
            FileOutputStream fos = new FileOutputStream(pathName);
            fos.write(uploadFile.getBytes()); // 写入文件
            System.out.println("图片上传成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        String uploadImgPath = "file/static/" + pathPart + fileName;
        JSONObject respond = new JSONObject();
        respond.put("path", uploadImgPath);

        return respond;
    }

    @PostMapping("getInfoList")
    public List<Info> getInfoList(@RequestBody JSONObject requestJson){
//    @GetMapping("getInfoList")
//    public List<Info> getInfoList(int type,String value, int pageSize, boolean isFirst, int pageNum){
        int type = requestJson.getInteger("type");          //主要类型
        String value = requestJson.getString("value");      //次级分类
        boolean isFirst = requestJson.getBoolean("pageFirst");//是否为第一页
        int pageSize = requestJson.getInteger("pageSize");//一页加载数
        int pageNum = requestJson.getInteger("pageNum");  //要加载的页码
        int pageStart = PageUtils.pagesCalculate(isFirst,pageSize,pageNum); //加载起始
        System.out.println("从"+pageStart+"加载"+pageSize+"-pageNum"+pageNum+"-type"+type+"-value"+value+"-isFirst"+isFirst);
        if (isFirst){
            return infoService.getInfoList(type,value,pageStart,pageSize);
        }
        List<Info> returnList = infoService.getListContinue(type,value,pageStart,pageSize);
        return returnList;
    }

    @PostMapping("getList")
    public JSONObject getList(@RequestBody JSONObject requestJson){
        String type = requestJson.getString("type");      //主要类型
        String value = requestJson.getString("value");      //次级分类
        String name = requestJson.getString("name");      //作者名
        String title = requestJson.getString("title");      //标题名
        int pageSize = requestJson.getInteger("pageSize");//一页加载数
        int pageNum = requestJson.getInteger("pageNum");  //要加载的页码
        return infoService.list(type, value, name, title, pageNum, pageSize);
    }

    @PostMapping("getMyInfo")
    public List<Info> getMyInfo(@RequestBody JSONObject requestJson){
        String infoAuthor = requestJson.getString("infoAuthor");
        System.out.println("用户获得资讯"+infoAuthor);
        return infoService.getMyInfo(infoAuthor);
    }

    @PostMapping("alterSwiper")
    public boolean alterSwiper(@RequestBody JSONArray infoSwiperArray){
        try{
            for (int i = 0; i < infoSwiperArray.size(); i++){
                int infoId = infoSwiperArray.getJSONObject(i).getInteger("infoId");
                String infoSwiper = infoSwiperArray.getJSONObject(i).getString("infoSwiper");
                System.out.println("资讯"+infoId+"轮播"+infoSwiper);
                infoService.alterInfoSwiper(infoId, infoSwiper);
            }
            return true;
        }
        catch (Exception e){
            return false;
        }
    }

    @PostMapping("alterIndex")
    public boolean alterInfoRank(@RequestBody JSONArray infoSwiperArray){
        try{
            for (int i = 0; i < infoSwiperArray.size(); i++){
                int infoId = infoSwiperArray.getJSONObject(i).getInteger("infoId");
                String infoRank = infoSwiperArray.getJSONObject(i).getString("infoRank");
                System.out.println("资讯"+infoId+"排序"+infoRank);
                infoService.alterInfoIndex(infoId, infoRank);
            }
            return true;
        }
        catch (Exception e){
            return false;
        }
    }
}
